<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="采购单号" prop="purchaseOrderNo">
        <el-input
          v-model="queryParams.purchaseOrderNo"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['erp-orders:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['erp-orders:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['erp-orders:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['erp-orders:orders:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
        @click="handlePublishOrder"
        v-hasPermi="['erp-orders:orders:publish']"
        >发布订单</el-button>
      </el-col>
      <!-- 新增“合同上传”按钮 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
        size="mini"
        @click="handleUploadContract"
        v-hasPermi="['erp-orders:orders:uploadContract']"
        >合同上传</el-button>
      </el-col>
      <!-- 新增“强制完结”按钮 -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-check"
        size="mini"
          @click="zhongzhi"
          :disabled="multiple"
        >强制完结</el-button>
      </el-col>
      <!-- 新增“打印”按钮 -->
      <el-col :span="1.5">
        <el-button
          type="default"
          plain
          icon="el-icon-print"
          size="mini"
          @click="handlePrint"
          v-hasPermi="['erp-orders:orders:print']"
        >打印</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="ordersList" @selection-change="handleSelectionChange"   @expand-change="handleRowClick"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购单号" align="center" prop="purchaseOrderNo" />
      <el-table-column type="expand">
      </el-table-column>
      <el-table-column label="供应商名称" align="center" prop="supplierFullName" />
      <el-table-column label="供应商简称" align="center" prop="supplierShortName" />
      <el-table-column label="来源单据" align="center" prop="sourceDoc" />
      <el-table-column label="不含税单价" align="center" prop="priceWithoutTax" />
      <el-table-column label="税价总计" align="center" prop="taxIncludedTotal" />
      <el-table-column label="税率" align="center" prop="taxRate" />


      <el-table-column label="arm状态" align="center" prop="status" >
        <template slot-scope="scope">
          <!-- 使用Element的Tag组件，根据状态动态设置type -->
          <el-tag
            :type="getStatusType(scope.row.status)"
            :disable-transitions="false"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="采购日期" align="center" prop="purchaseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到货日期" align="center" prop="daohurq" />
      <el-table-column label="采购总金额" align="center" prop="totalprice" />



      <el-table-column label="单据状态" align="center" prop="docStatus"  :formatter="formatdocStatus" >

        <template slot-scope="scope">
          <!-- 使用Element的Tag组件，根据状态动态设置type -->
          <el-tag
            :type="getdocStatusType(scope.row.docStatus)"
            :disable-transitions="false"
          >
            {{ getdocStatusText(scope.row.docStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="formatAuditStatus">
        <template slot-scope="scope">
          <!-- 使用Element的Tag组件，根据状态动态设置type -->
          <el-tag
            :type="getStatusType(scope.row.auditStatus)"
            :disable-transitions="false"
          >
            {{ getStatusText(scope.row.auditStatus) }}
          </el-tag>
        </template>

      </el-table-column>























      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['erp-orders:orders:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['erp-orders:orders:remove']"
          >删除</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRowClick(scope.row)"
            v-hasPermi="['erp-orders:orders:edit']"
          >查看物料</el-button>
        </template>
      </el-table-column>
    </el-table>





    <!-- 添加或修改采购单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购单号" prop="purchaseOrderNo">
          <el-input v-model="form.purchaseOrderNo" placeholder="请输入采购单号" />
        </el-form-item>
        <el-form-item   label="asm状态" prop="status">
          <el-input v-model="form.status" placeholder="请输入采购单号" />
        </el-form-item>
        <el-form-item label="采购日期" prop="purchaseDate">
          <el-date-picker clearable
                          v-model="form.purchaseDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择采购日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到货日期" prop="daohuorq">
          <el-input v-model="form.daohuorq" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="来源单据" prop="sourceDoc">
          <el-input v-model="form.sourceDoc" placeholder="请输入来源单据" />
        </el-form-item>
        <el-form-item label="采购总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入采购总金额" />
        </el-form-item>
      </el-form>
      <div  slot="footer" class="dialog-footer" label-width="150">
        <el-button type="primary"   @click="saveForm" :class="{ 'hidden': baocun }" :disabled="baocun">保存</el-button>
        <el-button type="primary" v-if="isEditMode" @click="auditForm">审核并新增</el-button>
        <el-button type="primary" :class="{ 'hidden': shenhe }" v-else @click="showApprovalDialog" :disabled="shenhe">仅审核</el-button>

        <el-button type="primary" @click="tijiao"  v-if="isEditMode"  >提交并新增</el-button>
        <el-button type="primary" :class="{ 'hidden': tijiaoaudit }" :disabled="tijiaoaudit" v-else @click="updatetijiao"   >仅提交</el-button>
        <el-button  size="mini"
                    plain
                    type="primary"
                    icon="el-icon-delete"
                    @click="jilu"
                    :disabled="single"

        >
          查看历史记录</el-button>
        <el-button @click="fqshenhe"  :disabled="qishenjc" :class="{ 'hidden': qishenjc }">弃审</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <!-- 触发按钮 -->
      <el-button
        type="primary"
        @click="showSelector"
      >
        <i class="el-icon-folder-opened"></i> 选择物料
      </el-button>

      <!-- 物料选择弹窗 -->
      <el-dialog
        title="选择物料"
        :visible.sync="xuanzewuliao"
        width="47%"
        top="10vh"
      >
        <!-- 搜索栏 -->
        <div style="margin-bottom: 15px">
          <el-input
            placeholder="输入物料编码或名称搜索"
            style="width: 300px"
            clearable
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>

        <!-- 物料表格 -->
        <el-table
          ref="multipleTable"
          :data="selectedMaterials"
          border
          style="width: 100%"
          height="400"
          @selection-change="handleSelectionChange3"
        >
          <el-table-column
            type="selection"

            width="55"
          ></el-table-column>
          <el-table-column prop="materialCode" label="物料编码" width="120" sortable/>
          <el-table-column prop="materialName" label="物料名称" width="180" show-overflow-tooltip/>
          <el-table-column prop="specification" label="规格型号" width="150"/>
          <el-table-column prop="unit" label="单位" width="100" align="center"/>
          <el-table-column prop="categoryName" label="分类" width="120"/>
          <el-table-column prop="stockQuantity" label="当前库存" width="120" align="right"/>
        </el-table>

        <!-- 分页和确认按钮 -->
        <div style="margin-top: 20px; display: flex; justify-content: space-between">


          <div slot="footer" class="dialog-footer">
            <!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->




          </div>
        </div>
      </el-dialog>

    </el-dialog>



    <!--强制终止的页面-->
    <el-dialog
      title="终止"
      :visible.sync="zhongzhiopen"
      width="30%"
      :before-close="handleClose">

      <el-form  label-width="100px" :model="this.from3">
        <el-form-item label="终止原因">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入终止原因"
            v-model="from3.reason">
            <!--            //后端前端交互数据的依据就是名称-->
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="zhongzhis">确 定</el-button>
      </span>
    </el-dialog>



    <!--审核记录的页面-->

    <el-dialog
      title="审核记录表"
      :visible.sync="jiludialog"
      width="80%"
      :before-close="handleClose">
      <el-table v-loading="loading" :data="jiluList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="记录ID" align="center" prop="id" />
        <el-table-column label="业务ID" align="center" prop="businessId" />
        <el-table-column label="业务类型" align="center" prop="businessType" />
        <!--        <el-table-column label="审批节点" align="center" prop="approvalNode" />-->
        <el-table-column label="审批人" align="center" prop="approver" />
        <el-table-column label="审批时间" align="center" prop="approvalTime" />
        <el-table-column label="审批结果" align="center" prop="result" :formatter="formatAuditStatus" />
        <el-table-column label="审批意见" align="center" prop="opinion" />
        <el-table-column label="上一级审批人" align="center" prop="previousApprover" />
        <el-table-column label="下一级审批人" align="center" prop="nextApprover" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="更新时间" align="center" prop="updateTime"  />
        <el-table-column label="删除状态" align="center" prop="deleted"  />
        <el-table-column label="流程状态" align="center" prop="processStatus"  />
      </el-table>
    </el-dialog>



    <!--审批的页面-->

    <el-dialog
      title="审批"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">

      <el-form  label-width="100px" :model="form2">
        <el-form-item label="审批意见">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入审批意见"
            v-model="form2.opinion">
          </el-input>
        </el-form-item>

        <el-form-item label="审批结果" >
          <el-radio-group v-model="choices">
            <el-radio label="agree">同意</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateshenhe">确 定</el-button>
      </span>
    </el-dialog>






    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看物料细目 -->
    <el-dialog
      title="选择物料"
      :visible.sync="wuliaoximu"
      width="47%"
      top="10vh"
    >
      <!-- 搜索栏 -->
      <div style="margin-bottom: 15px">
        <el-input
          placeholder="输入物料编码或名称搜索"
          style="width: 300px"
          clearable
        >
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <el-table
        ref="multipleTable"
        :data="selectedMaterials"
        border
        style="width: 100%; margin: 16px 0; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);"
        height="400"
        @selection-change="handleSelectionChange3"
        :header-cell-style="{
    'background-color': '#f5f7fa',
    'color': '#303133',
    'font-weight': '500',
    'border-bottom': '1px solid #e8e8e8'
  }"
        :row-style="{
    'transition': 'background-color 0.2s',
    '&:hover': {
      'background-color': '#fafafa'
    }
  }"
        :cell-style="{
    'border-bottom': '1px solid #e8e8e8',
    'padding': '12px 0'
  }"
      >
        <el-table-column
          type="selection"
          width="60"
          :selectable="(row, index) => true"
        ></el-table-column>

        <el-table-column
          prop="materialCode"
          label="物料编码"
          width="140"
          sortable
          :sort-orders="['ascending', 'descending']"
        >
          <template #default="scope">
            <span style="color: #1890ff; font-weight: 400;">{{ scope.row.materialCode }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="materialName"
          label="物料名称"
          width="200"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div style="display: flex; align-items: center;">
              <span>{{ scope.row.materialName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="specification"
          label="规格型号"
          width="160"
        ></el-table-column>

        <el-table-column
          prop="unit"
          label="单位"
          width="100"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="categoryName"
          label="分类"
          width="130"
        >
          <template #default="scope">
      <span class="category-tag" :style="{
        'background-color': getCategoryColor(scope.row.categoryName),
        'color': '#fff',
        'padding': '2px 8px',
        'border-radius': '4px',
        'font-size': '12px'
      }">
        {{ scope.row.categoryName }}
      </span>
          </template>
        </el-table-column>

        <el-table-column
          prop="stockQuantity"
          label="当前库存"
          width="140"
          align="right"
        >
          <template #default="scope">
      <span :style="{
        'color': scope.row.stockQuantity <= 10 ? '#f56c6c' : '#67c23a',
        'font-weight': scope.row.stockQuantity <= 10 ? '500' : 'normal'
      }">
        {{ scope.row.stockQuantity }}
        <span style="color: #606266; margin-left: 4px;">{{ scope.row.unit }}</span>
      </span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页和确认按钮 -->
      <div style="margin-top: 20px; display: flex; justify-content: space-between">


        <div>
          <el-button @click="xuanzewuliao = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection" v-if="qrxz">确认选择</el-button>
          <el-button type="primary" @click="confirmSelection2" v-else  if="qrxz">确认选择</el-button>

        </div>
      </div>
    </el-dialog>








  </div>
</template>

<script>
import {getOrders, getpurchaseOrders, orderwuliaoId, wuliao, zhongzhi} from "../../../api/erp-orders/orders";
import {selectsupper} from "../../../api/purchase/purchase";

export default {
  name: "Orders",
  data() {
    return {
      uid:'',
      tijiaoaudit:true,
      shenhe:true,
      baocun:false,
      form2:{},
      dialogVisible: false,//审核弹出框 同意或拒绝
      isDisabled: false, // 设置为true禁用按钮      // 遮罩层
      isEditMode: true,
      choices:'',
      choice:'', //选中 0拒绝 1同意
      opinion:'', //审核意见
      from3:{},
      zhongzhiid:[],
      zhongzhiopen:false,
      jiludialog:false,
      jiluList:[],
      wuliaoList:[],
      xuanzewuliao:false,
      selectedMaterials: [], // 当前选择的物料
      wuliaoids:[], //收集加入物料的id
      multipleSelection: [], //判断选择的的物料是否重复
      qishenjc:true,
      xiugaibtn:false,
      qrxz:true,
      details: [] /* 详细数据对象 */ ,



      wuliaoximu:false,





























      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单管理表格数据
      ordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseOrderNo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        purchaseOrderNo: [
          { required: true, message: "采购单号不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // getpurchaseOrders();
  },
  methods: {

    async handleRowClick(row) {
      this.wuliaoximu=true
      this.details=await orderwuliaoId(row.id)
      console.log( "订单的物料",this.details)

      console.log( "订单的id",row.id)

    },











    async wuliaodelete(row){
      console.log(this.uid,"物料id"+row.id)
      const res = await wuliaodelete(this.uid,row.id);
      if (res>0){
        this.$message.success("删除物料成功");
      }
      this.$message.success("删除物料失败");

    },



    async fqshenhe() {
      try {
        const res = await qishen(this.uid); // 调用弃审API
        if (res.code === 200) { // 假设200表示成功
          this.$message.success("弃审成功！");
          // 刷新数据或更新状态
          this.purchaseList();
        } else {
          this.$message.error(`弃审失败：${res.msg}`);
        }
      } catch (error) {
        this.$message.error("请求异常，请检查网络或联系管理员");
      }
    },

    async confirmSelection() {
      // if (this.multipleSelection.length === 0) {
      //   this.$message.warning('请至少选择一项物料')
      //   return
      // }
      console.log(this.wuliaoids)
      console.log(this.uid)
      const  data=await  wuliaoadd(this.wuliaoids,this.uid)
      if(data===1){
        this.$message.success("加入成功")
        this.xuanzewuliao = false;
        await this.wuliao()

      }
      this.$message.error("加入失败")




      // 这里处理选中的数据
      console.log('已选择物料:', this.multipleSelection)
      this.xuanzewuliao = false
      this.$emit('material-selected', this.multipleSelection)
    },
    async confirmSelection2() {
      // if (this.multipleSelection.length === 0) {
      //   this.$message.warning('请至少选择一项物料')
      //   return
      // }
      this.xuanzewuliao = false
      console.log(this.wuliaoids)
      console.log(this.uid)

      // 这里处理选中的数据
      console.log('已选择物料:', this.multipleSelection)
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },

    // 物料多选框选中数据
    handleSelectionChange3(selection) {
      this.wuliaoids = selection.map(item => item.id)
      console.log(this.wuliaoids)
      // if (!this.multiple && selection.length > 1) {
      //
      //   // 单选模式下取消之前的选择
      //
      //   const lastSelected = selection[selection.length - 1]
      //   this.$refs.multipleTable.clearSelection()
      //   this.$refs.multipleTable.toggleRowSelection(lastSelected, true)
      //   this.selectedMaterials = [lastSelected]
      // } else {
      //   this.selectedMaterials = selection
      // }
    },

    async showSelector() {
      this.xuanzewuliao = true
      const  data=  await  selectmaterials()
      console.log("物料数据为1"+data);
      this.selectedMaterials=data;
      console.log( "物料数据为"+this.selectedMaterials);
      this.getList()
    },
    getdocStatusType(status) {
      switch(status) {
        case 0: return 'info';    // 待提交 - 使用Element的info类型（蓝色）
        case 1: return 'warning'; // 已提交 - 使用Element的warning类型（橙色）
        case 2: return 'success'; // 审核完成 - 使用Element的success类型（绿色）
        default: return 'danger';       // 已终止使用自定义颜色
      }
    },

    // 根据状态获取Tag的类型（Element UI内置的颜色类型）
    getStatusType(status) {
      switch(status) {
        case 0: return 'info';    // 草稿 - 蓝色
        case 1: return 'warning'; // 未审核 - 橙色
        case 2: return 'success'; // 已审核 - 绿色
        default: return 'danger'; // 未知状态 - 红色
      }
    },
    getdocStatusText(status) {
      const statusMap = {
        0: '待提交',
        1: '已提交',
        2: '审核完成',
        3: '已终止'
      };
      return statusMap[status] || '未知状态';
    },
    // 根据状态获取显示文本
    getStatusText(status) {
      const statusMap = {
        0: '草稿',
        1: '待审核',
        2: '已审核',
        3: '拒绝',
        4: '审核完成',
        5: '强制终止'
      };
      return statusMap[status] || '未知状态';
    },


    showApprovalDialog() {
      this.dialogVisible = true
    },


    updatetijiao() {
      console.log(this.uid);
      updatetijiao(this.uid).then(response => {
        this.form = response.data;
        this.getList();
      });
    },
    updateshenhe() {
      console.log(this.uid);
      console.log(this.form2.opinion);
      if (this.form2.opinion===''||this.form2.opinion==null) {
        this.$message.warning('请输入审批意见')
        return
      }
      // 提交审批逻辑
      console.log('提交审批:', this.opinion)
      // 根据结果执行不同操作
      if (this.choices === 'agree') {
        this.choice=1
      } else {
        this.choice=0
      }
      // 关闭弹窗
      this.dialogVisible = false
      // 重置表单
      this.resetForm()
      console.log(this.choice);
      updateshenhe(this.uid,this.form2.opinion,this.choice).then(response => {
        this.getList();
      }).catch(error => {
        console.log(error.response.data.msg); // 失败时："审核失败"
      });
    },
    handleClose(done) {
      // 关闭前的回调
      this.$confirm('确定要关闭审批窗口吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done()
        this.resetForm()
      }).catch(() => {})
    },
    resetForm() {
      this.approvalForm = {
        opinion: '',
        result: 'agree'
      }
    },

    saveForm() {
      console.log(this.wuliaoids)
      this.form.auditStatus=0
      console.log('保存表单:', this.form);
      baocun(this.form,this.wuliaoids).then(response => {});
      this.$message.success('保存成功');
      this.open=false
    },

    auditForm() {
      this.form.status
      console.log('审核表单:', this.form);
      shenhe(this.form).then(response => {
        this.managementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.$message.info('已提交审核');
    },
    tijiao() {
      this.form.status
      console.log('提交表单:', this.form);
      tijiao(this.form).then(response => {
        this.managementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.
      this.$message.success('审核成功');
    },



    formatAuditStatus(row, column, cellValue) {
      const statusMap = {
        0: '草稿',
        1: '待审核',
        2: '已审核',
        3: '拒绝',
        4: '审核完成',
        5: '强制终止'
      }
      return statusMap[cellValue] || '未知状态'
    },
    formatdocStatus(row, column, cellValue) {
      const statusMap = {
        0: '待提交',
        1: '已提交',
        2: '审核完成',
        3: '已终止'
        // 其他状态码可继续扩展...
      }
      return statusMap[cellValue] || '未知状态'
    }
    ,


    zhongzhi(row) {
      alert(1)
      const ids = row.id || this.ids;
      console.log(ids);
      this.zhongzhiid = ids;

      this.reset();
      this.zhongzhiopen = true;
    },




    zhongzhis() {
      this.$modal.confirm(`是否确认终止请购单管理编号为"${this.zhongzhiid}"的数据项？`)
        .then(() => {  // 使用箭头函数保持this指向
          // 确保zhongzhi函数是可访问的，且参数正确
          console.log(this.zhongzhiid)
          return zhongzhi(this.zhongzhiid, this.from3.reason);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("强制终止成功");
        })
        .catch(() => {
          // 最好在这里添加错误处理
        });
    },

    isxiugaioder(order) {
      return order.auditStatus === 2||order.auditStatus === 3||order.auditStatus === 5  ;

    },
    isButtonEnabled(order) {
      return order.auditStatus === 0 || order.auditStatus === 1;
    },
    async jilu() {
      this.loading = true;
      try {
        const  data  = await jilu(this.uid);
        console.log(data);
        this.jiluList = data;
        this.jiludialog = true;

        // 更新UI状态
        this.open = false;
        this.jiludialog = true;

        // 如果需要刷新列表
        this.getList();
      } catch (error) {
        console.error('获取审批记录失败:', error);
        this.$message.error('获取审批记录失败');
      } finally {
        this.loading = false;
      }
    },












    /** 查询采购单管理列表 */
    getList() {
      this.loading = true;
      getpurchaseOrders(this.queryParams).then(response => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        purchaseOrderNo: null,
        supplierId: null,
        purchaseRequestId: null,
        purchaseDate: null,
        totalAmount: null,
        status: null,
        daohuorq:null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购单管理";
    },
    /** 修改按钮操作 */
   async handleUpdate(row) {
      const id = row.id || this.ids
      this.uid=id;
      const data = await wuliao(this.uid)
      this.supplierslist = await selectsupper();
      console.log("供应商"+this.supplierslist)
      console.log("物料数据为1"+data);
      this.wuliaoList=data;
      console.log( "物料数据为"+this.wuliaoList);
      this.isEditMode=false
      this.baocun=true
      this.reset();

      getOrders(this.uid).then(response => {
        this.form = response.data;
        console.log(this.form.status)
        if (this.form.auditStatus===1){
          this.shenhe=false
          this.qishenjc=true;

          this.tijiaoaudit=true;

        }
        if (this.form.auditStatus===2){
          this.tijiaoaudit=true;
          this.qishenjc=false;

          this.shenhe=true

        }
        //提交
        if(this.form.auditStatus===0){
          this.qishenjc=true;
          this.tijiaoaudit=false;
        }
        this.open = true;
        this.title = "修改请购单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购单管理编号为"' + ids + '"的数据项？').then(function() {
        return delOrders(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp-orders/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.status-table-container {
  padding: 20px;
}

/* 可选：为不同状态的行添加轻微背景色 */
::v-deep .el-table .table-row {
  transition: background-color 0.2s;
}

/* 利用行的class配合状态过滤选择器 */
::v-deep .el-table .table-row:nth-child(5n+1) {
  /* 这里可以根据实际需求通过JS动态添加行class */
}

/* 悬停效果增强 */
::v-deep .el-table__row:hover > td {
  background-color: #f5f7fa !important;
}
.butcolor{
  background-color: red;
}

.hidden {
  display: none;
}










.compact-table .el-table td,
.compact-table .el-table th {
  padding: 6px 0;
}

.compact-table .el-table .cell {
  line-height: 1.2;
  white-space: nowrap;
}

.compact-table .el-table {
  border-collapse: collapse;
}

/* 按钮紧凑样式 */
.compact-table .el-button--mini {
  padding: 5px 8px;
  margin: 0 2px;
}
</style>
